package com.tim.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tim.pojo.DataResult;
import com.tim.pojo.Plot;
import com.tim.service.Impl.PlotServiceImpl;
import com.tim.service.PlotService;
import com.tim.util.ExcelUtils;
import com.tim.util.FileUploadUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者：Tim
 * 时间：2021/4/25 17:15
 */
@WebServlet("/plot/*")
@MultipartConfig
public class PlotServlet extends BaseServlet{
    PlotService plotService = new PlotServiceImpl();
    /**
     * 查询所有
     */
    public DataResult all(HttpServletRequest request, HttpServletResponse response) {
        //1、获取请求参数
        List<Plot> plotList = plotService.selectAll();
        DataResult dataResult;
        if(plotList!=null){
            dataResult = new DataResult(0,"查询成功",plotList);
            return dataResult;
        }else{
            dataResult = new DataResult(40000,"查询失败");
            return dataResult;
        }
    }

    /**
     * 分页查询所有
     */
    public DataResult selectAll(HttpServletRequest request, HttpServletResponse response) {
        //1、获取请求参数
        String page = request.getParameter("page");
        String limit=request.getParameter("limit");
        //获取模糊查询的数据
        String plotName = request.getParameter("plotName");
        //2、调用service业务方法
        DataResult dataResult = plotService.limit(page, limit,plotName);
        //3、做出响应
        return dataResult;
    }

    /**
     * 删除
     */
    public DataResult del(HttpServletRequest request,HttpServletResponse response){
        //1、获取请求参数
        String id = request.getParameter("id");
        //2、调用Service层方法
        int count = plotService.deletePlot(id);
        DataResult dataResult ;
        if(count>0){
            dataResult = new DataResult(0,"删除成功");
        }else{
            dataResult = new DataResult(40000,"删除失败");
        }
        return dataResult;
    }

    /**
     * 添加
     */
    public DataResult add(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {
        //1、获取请求参数
        String info = request.getParameter("info");
        //将前端传递的json字符串转换成java对象
        ObjectMapper mapper = new ObjectMapper();
        Plot plot = mapper.readValue(info, Plot.class);
        //2、调用Service层方法
        PlotService plotService = new PlotServiceImpl();
        int count = plotService.addPlot(plot);
        DataResult dataResult ;
        if(count>0){
            dataResult = new DataResult(0,"添加成功");
        }else{
            dataResult = new DataResult(40000,"添加失败");
        }
        return dataResult;
    }

    /**
     * 上传图片
     */
    public DataResult upload(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {
        DataResult dataResult;
        try {
            //调用工具类上传文件
            String sqlPath = FileUploadUtil.upload(request);
            //将地址返回到前端
            dataResult = new DataResult(0,"上传成功",sqlPath);
        } catch (Exception e) {
            e.printStackTrace();
            dataResult = new DataResult(40000,"上传失败");
        }
        return dataResult;
    }
    /**
     * 根据id查询
     */
    public DataResult one(HttpServletRequest request,HttpServletResponse response){
        String id = request.getParameter("id");
        Plot plot = plotService.selectOne(id);
        DataResult dataResult;
        if(plot==null){
            dataResult=new DataResult(40000,"查无结果");
        }
        dataResult = new DataResult(0,"查询成功",plot);
        return dataResult;
    }

    /**
     *  修改编辑
     */
    public DataResult update(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {
        //1、获取请求参数
        String info = request.getParameter("info");
        //将前端传递的json字符串转换成java对象
        ObjectMapper mapper = new ObjectMapper();
        Plot plot = mapper.readValue(info, Plot.class);
        //2、调用Service层方法
        PlotService plotService = new PlotServiceImpl();
        int count = plotService.updatePlot(plot);
        DataResult dataResult ;
        if(count>0){
            dataResult = new DataResult(0,"修改成功");
        }else{
            dataResult = new DataResult(40000,"修改失败");
        }
        return dataResult;
    }

    /**
     *      删除多个
     */
    public DataResult delAll(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {
        //1、获取请求参数(ids)   JSON字符串（数组）
        String ids = request.getParameter("ids");
        //通过Jackson将json字符串转换成java对象
        ObjectMapper mapper = new ObjectMapper();
        String[] idArr = mapper.readValue(ids, String[].class);

        //2、调用Service层方法
        PlotService plotService = new PlotServiceImpl();
        int count = plotService.deleteAll(idArr);
        DataResult dataResult;
        if(count>0){
            dataResult = new DataResult(0,"删除"+count+"条数据成功");
        }else{
            dataResult = new DataResult(40000,"删除失败");
        }
        return dataResult;
    }

    public Map eachartsData(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {
        //需要的数据有哪些？   1、所有的部门名称的数组。   2、所有的部门人数的数组


        //1、调用Service方法获取所有部门对象，部门的员工数量
        List<Plot> plotList = plotService.selectAll();
        String[] xData = new String[plotList.size()];
        String[] yData = new String[plotList.size()];
        for (int i = 0; i < plotList.size(); i++) {
            xData[i] = plotList.get(i).getPlotName();
        }

//        int[] yData = plotService.deptCount(plotList);
        for (int i = 0; i < plotList.size(); i++) {
            yData[i] = String.valueOf(plotList.get(i).getGreenRate());
        }

        Map<String,Object> map = new HashMap<>();
        map.put("code",0);
        map.put("xData",xData);
        map.put("yData",yData);
        return  map;
    }

    /**
     * 上传excel表格
     */
    public DataResult uploadExcel(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {
        //1、根据上传的文件获取文件的输入流对象
        Part part = request.getPart("file");
        InputStream in = part.getInputStream();
        //2、获取上传文件的后缀名
        String fileName = part.getSubmittedFileName();
        String fileExt = fileName.substring(fileName.lastIndexOf(".")+1);

        //3、调用工具类的中导入方法
        List<String[]> data = ExcelUtils.importData(fileExt, in, 1);
        //4、调用Service层方法，将数据插入数据库
        PlotService plotService = new PlotServiceImpl();
        int count = plotService.addAllPlot(data);
        DataResult dataResult;
        if(count>0){
            dataResult = new DataResult(0,"添加"+count+"条数据成功");
        }else{
            dataResult = new DataResult(40000,"添加失败");
        }
        return dataResult;
    }

    /**
     *导出为Excel
     */
    public void downloadExcel(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {
        //1、获取所有的Plot数据
        PlotService plotService = new PlotServiceImpl();
        List<Plot> plotList = plotService.selectAll();

        //设置响应头，告知浏览器是下载操作
        response.setHeader("Content-Disposition","attachment;filename=table.xls");
        //设置MIME类型
        response.setContentType("application/vnd.ms-excel");

        //2、将PlotList转换成Excel表格
        //定义表格头
        String[] titles = {"ID","小区编号","小区名称","坐落地址","占地面积(㎡)","总栋数","总户数","绿化率（%）","缩略图","开发商名称","物业公司名称","创建时间","状态"};
        //将plotList转换成List<String[]>的数据格式
        ExcelUtils.export(titles,toArray(plotList),response.getOutputStream());
    }

    /**
     *
     * @param plotList
     * @return
     */
    private List<String[]> toArray(List<Plot> plotList) {
        List<String[]> data = new ArrayList<>();
        for(Plot plot:plotList){
            String[] row = new String[13];
            row[0] = String.valueOf(plot.getId());
            row[1] = plot.getPlotNum();
            row[2] = plot.getPlotName();
            row[3] = plot.getPlotLocation();
            row[4] = String.valueOf(plot.getPlotArea());
            row[5] = String.valueOf(plot.getBuildNum());
            row[6] = String.valueOf(plot.getFamilyNum());
            row[7] = String.valueOf(plot.getGreenRate());
            row[8] = plot.getImage();
            row[9] = plot.getDeveloper();
            row[10] = plot.getTenementName();
            row[11] = new SimpleDateFormat("yyyy-MM-dd").format(plot.getDatecreated());
            row[12] = String.valueOf(plot.getStatus());
            data.add(row);
        }
        return data;
    }
}
